package com.wxg.util;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *
 * date : 2018年9月28日
 *
 * 失败的实验, 没法达到 Python 的 range 那样的便捷功能
 *
 */
public class Range {

    public static Iterable r(int start, int end, int step){
        return new DefaultIterable(start, end, step);
    }

    private static class DefaultIterable implements Iterable<java.lang.Integer> {
        private final int end;
        private final int step;
        private int current;

        public DefaultIterable(int start, int end, int step) {
            this.end = end;
            this.step = step;
            current = start - step;
        }

        @Override
        public Iterator iterator() {
            return new Iterator() {
                @Override
                public boolean hasNext() {
                    return (current + step) >= end;
                }

                @Override
                public Integer next() {
                    current += step;
                    if (current <= end) {
                        return current;
                    } else {
                        throw new NoSuchElementException();
                    }
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    }

    public static void main(String[] args) {
        // for (int x : Range.r(1, 10, 1)){}
        Iterable x = Range.r(1, 10, 1);
//        for (int a : x){}
    }
}
